package com.example.zqh.controller;

//import com.example.shoping.config.redis.RedisUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

@RestController
public class KaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

//    @Autowired
//    RedisUtils redisUtils;

    @ApiOperation(value = "制作一个验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");



        String key = UUID.randomUUID().toString();


        //获取验证码文本类容
        String text = defaultKaptcha.createText();
        System.out.println("验证类容+"+text);
        //将验证文本类容放入session
        request.getSession().setAttribute("captcah",text);
        //根据文本验证码类容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
//        redisUtils.hset("captcha",key,text,120);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null!=outputStream){
                try {
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }



    }
}
